﻿Public Class CharCodeRule
    Inherits ValidationRule

    Public Overloads Overrides Function Validate(value As Object, cultureInfo As Globalization.CultureInfo) As ValidationResult
        If value Is Nothing Then

        End If

        Dim strVal As String = DirectCast(value, String)
        Dim intVal As Integer
        If Integer.TryParse(strVal, intVal) Then
            'test if in range of 0 to 255
            If intVal < 0 OrElse intVal > 255 Then
                Return New ValidationResult(False, "Value must be between 0 and 255")
            End If

            Return Nothing
        Else
            'test to make sure it is a single char enclosed in single quotes
            If strVal.Length <> 3 Then
                Return New ValidationResult(False, "Value must be a single character enclosed in single-quotes")
            End If

            If Not strVal.StartsWith("'") OrElse Not strVal.EndsWith("'") Then
                Return New ValidationResult(False, "Value must be a single character enclosed in single-quotes")
            End If

            Dim ascii As Integer = Convert.ToInt32(strVal(1))
            If ascii < 0 OrElse ascii > 255 Then
                Return New ValidationResult(False, "Value must be character with an ASCII code between 0 and 255")
            End If
        End If

        Return New ValidationResult(True, Nothing)
    End Function
End Class
